package cn.xuguowen.config;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * ClassName: GarbageWebSocketServerConfig
 * Package: cn.xuguowen.config
 * Description: 关于websocket服务的一些配置信息:鉴权
 *
 * @Author 徐国文
 * @Create 2023/5/22 0:08
 * @Version 1.0
 */
@Component
public class GarbageWebSocketServerConfig extends ServerEndpointConfig.Configurator {
    /**
     * 服务的鉴权
     * @param originHeaderValue
     * @return
     */
    @Override
    public boolean checkOrigin(String originHeaderValue) {
        // ServletRequestAttributes这个类实现了RequestAttributes这样的一个接口
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        // 有了上面的这个对象，就可以获取request对象
        HttpServletRequest request = servletRequestAttributes.getRequest();

        // 接下来就可以通过request对象获取请求的信息，判断其是否需要进行鉴权！

        // 鉴权成功则返回true
        return true;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 1.通过request对象获取到所有的请求参数
        Map<String, List<String>> parameterMap = request.getParameterMap();

        List<String> erpList = parameterMap.getOrDefault("erp", null);

        if (!CollUtil.isEmpty(erpList)) {
            sec.getUserProperties().put("erp",erpList.get(0));
        }

    }
}
